package club.kynb.mall.basic.gateway;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author kynb_club@163.com
 * @since 2021/6/24 3:05 下午
 */
@Slf4j
@Component
public class SmsGatewayImpl implements SmsGateway {

    @Value("${SMS.SIGN_NAME}")
    private String signName;
    @Value("${SMS.ACCESS_KEY_ID}")
    private String accessKeyId;
    @Value("${SMS.ACCESS_KEY_SECRET}")
    private String accessSecret;
    @Value("${SMS.REGION_ID}")
    private String regionId;

    @Override
    public void send(String phone, String templateId, String code) throws Exception {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateId);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        CommonResponse response = client.getCommonResponse(request);
        log.info("阿里云短信发送：{}，响应结果：{}", phone, response);
        if (!response.getHttpResponse().isSuccess()) {
            throw new RuntimeException("阿里云短信发送失败：" + response.getHttpResponse().getReasonPhrase());
        }
    }
}
